package com.dnjn.happiness.biz.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dnjn.happiness.biz.domain.Communicate;
import com.dnjn.happiness.biz.domain.HistoryInterview;
import com.dnjn.happiness.biz.service.ICommunicateService;
import com.dnjn.happiness.biz.service.IHistoryInterviewService;
import com.dnjn.happiness.common.core.constant.SecurityConstants;
import com.dnjn.happiness.common.core.domain.R;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.common.core.utils.poi.ExcelUtil;
import com.dnjn.happiness.common.cloud.controller.BaseController;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.common.log.annotation.Log;
import com.dnjn.happiness.common.log.enums.BusinessType;
import com.dnjn.happiness.common.security.annotation.RequiresPermissions;
import com.dnjn.happiness.common.security.utils.SecurityUtils;
import com.dnjn.happiness.system.api.RemoteDeptService;
import com.dnjn.happiness.system.api.RemoteUserService;
import com.dnjn.happiness.system.api.domain.SysDept;
import com.dnjn.happiness.system.api.domain.SysUser;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

/**
 * 历史沟通记录Controller
 *
 * @author happiness
 * @date 2023-11-20
 */
@Tag(name = "biz interview 历史沟通记录", description = "历史沟通记录")
@RestController
@RequestMapping("/interview")
public class HistoryInterviewController extends BaseController {
    @Autowired
    private IHistoryInterviewService historyInterviewService;

    @Autowired
    private RemoteDeptService deptService;

    @Autowired
    private RemoteUserService userService;

    @Autowired
    private ICommunicateService communicateService;

    /**
     * 查询历史沟通记录列表
     */
    @PostMapping("/list")
    @Log(title = "biz", businessType = BusinessType.LIST)
    @RequiresPermissions("biz:interview:list")
    public AjaxResult list(@RequestBody HistoryInterview historyInterview, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Page page = Page.of(current, size);
//        Page<HistoryInterview> list = historyInterviewService.page(page,Wrappers.query(historyInterview));
        Page<HistoryInterview> list = historyInterviewService.getPage(page, historyInterview);
        for (HistoryInterview item : list.getRecords()) {
            Long userId = item.getUserId();
            Communicate communicate = communicateService.getCommunicateByUserId(userId);
            item.setCommunicate(communicate);
            Long deptId = item.getDeptId();
            if (!ObjectUtils.isEmpty(deptId)) {
                SysDept sysDept = null;
                R<SysDept> result = deptService.getInfoById(deptId, SecurityConstants.INNER);
                if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
                    sysDept = result.getData();
                }
                if (null == sysDept) {
                    continue;
                }
                if (null == sysDept.getLeaderId() || userId.equals(sysDept.getLeaderId())) {
                    Long parentId = sysDept.getParentId();
                    if (null == parentId) {
                        continue;
                    }
                    Long leaderId = null;
                    R<SysDept> resultDept = deptService.getInfoById(parentId, SecurityConstants.INNER);
                    if (StringUtils.isNotNull(resultDept) && StringUtils.isNotNull(resultDept.getData())) {
                        leaderId = resultDept.getData().getLeaderId();
                    }
                    if (!ObjectUtils.isEmpty(leaderId)) {
                        R<SysUser> userResult = userService.selectUserInfo(leaderId, SecurityConstants.INNER);
                        if (StringUtils.isNotNull(userResult) && StringUtils.isNotNull(userResult.getData())) {
                            item.setLeaderName(userResult.getData().getNickName());
                        }
                    }
                } else {
                    Long leaderId = sysDept.getLeaderId();
                    R<SysUser> userResult = userService.selectUserInfo(leaderId, SecurityConstants.INNER);
                    if (StringUtils.isNotNull(userResult) && StringUtils.isNotNull(userResult.getData())) {
                        item.setLeaderName(userResult.getData().getNickName());
                    }
                }
            }
        }
        return success(list);
    }

    /**
     * 导出历史沟通记录列表
     */
    @Log(title = "历史沟通记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @RequiresPermissions("biz:interview:export")
    public void export(HttpServletResponse response, HistoryInterview historyInterview) {

        List<HistoryInterview> list = historyInterviewService.list(Wrappers.query(historyInterview));
        ExcelUtil<HistoryInterview> util = new ExcelUtil<HistoryInterview>(HistoryInterview.class);
        util.exportExcel(response, list, "历史沟通记录数据");
    }

    /**
     * 获取历史沟通记录详细信息
     */
    @GetMapping(value = "/{id}")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    @RequiresPermissions("biz:interview:query")
    public AjaxResult get(@PathVariable("id") Long id) {
        return success(historyInterviewService.getById(id));
    }

    /**
     * 新增历史沟通记录
     */
    @Log(title = "历史沟通记录", businessType = BusinessType.INSERT)
    @PostMapping
    @RequiresPermissions("biz:interview:add")
    public AjaxResult add(@RequestBody HistoryInterview historyInterview) {
        historyInterview.setCreateBy(SecurityUtils.getUsername());
        return toAjax(historyInterviewService.save(historyInterview));
    }

    /**
     * 修改历史沟通记录
     */
    @Log(title = "历史沟通记录", businessType = BusinessType.UPDATE)
    @PutMapping
    @RequiresPermissions("biz:interview:edit")
    public AjaxResult edit(@RequestBody HistoryInterview historyInterview) {
        return toAjax(historyInterviewService.updateById(historyInterview));
    }

    /**
     * 删除历史沟通记录
     */
    @Log(title = "历史沟通记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @RequiresPermissions("biz:interview:remove")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(historyInterviewService.removeBatchByIds(Arrays.asList(ids)));
    }

    /**
     * 首页折线图，获取历史访谈人数 - 最近一个月的
     */
    @PostMapping("/getHistoryInterviewEcharts")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    @RequiresPermissions("biz:interview:query")
    public AjaxResult getHistoryInterviewEcharts(@Parameter(description = "yyyy-MM-dd") @RequestParam(required = false) String startTime, @RequestParam(required = false) @Parameter(description = "yyyy-MM-dd") String endTime) {
        //如果两个日期为空时，默认获取当前日期前一个月的
        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
            LocalDateTime endLocalDateTime = LocalDateTime.now();
            LocalDateTime startLocalDateTime = LocalDateTime.now().minusMonths(1);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            startTime = formatter.format(startLocalDateTime);
            endTime = formatter.format(endLocalDateTime);
        }
        List<HistoryInterview> list = historyInterviewService.getHistoryInterviewEcharts(startTime, endTime);
        return success(list);
    }

    /**
     * 今日新增沟通人数
     */
    @GetMapping("/todayAddInterviewCount")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    @RequiresPermissions("biz:interview:query")
    public AjaxResult todayAddInterviewCount() {
        Long count = historyInterviewService.lambdaQuery().eq(HistoryInterview::getCurrDate, LocalDate.now()).count();
        return AjaxResult.success(count);
    }

}
